package com.gy.training.ui;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.gy.training.R;
import com.gy.training.model.Fruit;
import com.gy.training.adapter.FruitAdapter;


import java.util.ArrayList;
import java.util.List;

public class FruitListActivity extends AppCompatActivity {
    private ListView listFruit;
    private List<Fruit> fruitList = new ArrayList<Fruit>();
    private FruitAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fruit_list);
        fruitList.add(new Fruit("Apple",R.drawable.apple));
        fruitList.add(new Fruit("Apricot",R.drawable.apricot));
        fruitList.add(new Fruit("Banana",R.drawable.banana));
        fruitList.add(new Fruit("Cherry",R.drawable.cherry));
        fruitList.add(new Fruit("Mihoutao",R.drawable.mihoutao));

        listFruit = (ListView)findViewById(R.id.list_fruit);
        adapter = new FruitAdapter(FruitListActivity.this,R.layout.fruit_item,fruitList);
        listFruit.setAdapter(adapter);

        super.registerForContextMenu(listFruit); //注册上下文菜单
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("选择操作");
        menu.add(Menu.NONE,Menu.FIRST+1,1,"删除");
        menu.add(Menu.NONE,Menu.FIRST+2,2,"添加");
        menu.add(Menu.NONE,Menu.FIRST+3,3,"取消");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo acmiRef = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); //获取Item信息
//        int removeIndex = item.getItemId();
        int removeIndex  = acmiRef.position;
        switch (item.getItemId()){
            case Menu.FIRST+1:
                fruitList.remove(removeIndex);
                adapter.notifyDataSetChanged();// 删除后刷新ListView
                break;
            case Menu.FIRST + 2:
                Toast.makeText(this,"add success",Toast.LENGTH_SHORT).show();
                break;
            case Menu.FIRST + 3:
                break;
            default:
                break;
        }
        return false;
    }
}
